package com.yc.cloud.socket.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.yc.cloud.socket.service.SocketClient;
import lombok.extern.slf4j.Slf4j;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import org.springframework.stereotype.Service;

/**
 * @author 杨智杰
 * @since 2021/9/24 13:41
 */
@Slf4j
@Service
public abstract class SocketClientImpl implements SocketClient {

    private WebSocketClient client = null;

    @Override
    public void onOpen(ServerHandshake serverHandshake) {
        log.info("开启了新的链接");
    }

    @Override
    public void onMessage(String s) {
        log.info("收到消息" + s);
    }

    @Override
    public void onClose(int i, String s, boolean b) {
        log.info("关闭了链接");
    }

    @Override
    public void onError(Exception e) {
        log.error(e.getMessage(), e);
    }

    @Override
    public void sendMessage(Object data){
        sendMessage(null, data);
        log.info("发送消息:" + JSONUtil.toJsonStr(data));
    }

    @Override
    public void sendMessage(WebSocketClient client, Object data) {
        if (ObjectUtil.isNull(this.client) && ObjectUtil.isNull(client)){
            try {
                throw new Exception("还未链接至socket服务器!无法发送消息!请先调用SocketClientUtil.linkSocket方法!");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (ObjectUtil.isNull(this.client) && ObjectUtil.isNotNull(client)) {
            this.client = client;
        }
        this.client.send(JSONUtil.toJsonStr(data));
    }
}
